/*
 * @Author: Sam
 * @Date: 2021-03-12 20:47:13
 * @LastEditTime: 2021-04-30 11:47:48
 * @LastEditors: Sam
 * @Description:
 * @FilePath: \resourcesf:\thework\ygboost-eui\src\utils\index.js
 * 可以输入预定的版权声明、个性签名、空行等
 */
/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
import store from '@/store'
import route from '@/router'
export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}


export function closeDialog () {
  store.dispatch('toggleModal');
  if (store.state.main.shouldReload && route.params.uri) {
    var path = route.path;
    var uri = route.params.uri;
    if (path.indexOf("/board") === 0) {
      store.dispatch('loadBoardEntry', uri);
    } else if (path.indexOf("/blank") === 0) {
      store.dispatch('loadBlankEntry', uri);
    } else if (path.indexOf("/mobile") == 0) {
      store.dispatch('saveMobileTitle', document.title);
      store.dispatch('loadMobileEntry', uri);
    } else {
      store.dispatch('loadMainEntry', uri);
      store.dispatch('loadPageData', uri);
      store.dispatch('switchActiveName', { name: '0' });
    }
  }
  store.state.edit.saved = '';
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime (time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

// 判断是否非空对象
export function isNoEmptyObject (target) {
  const type = typeof target
  return target !== null && type === 'object' && Object.keys(target).length > 0
}

/**
 * 空行检测
 * @param rows
 * @returns {Boolean}
 */
export function checkRowsEmpty (rows) {

  if (rows === null) {
    return false;
  }

  for (const i in rows) {
    if (rows[i] !== null && rows[i] !== '' || (Object.prototype.toString.call(rows[i]) === "[object Array]" && rows[i].length===0 )) {
      console.log('rows[i] :>> ', rows[i]);
      return true;
    }
  }

  return false;
}

/**
*  人民币小写金额转换为大写
*/
export const digitUppercase = (n) => {
  let fraction = ['角', '分']
  let digit = [
    '零', '壹', '贰', '叁', '肆',
    '伍', '陆', '柒', '捌', '玖'
  ];
  let unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ];
  let head = n < 0 ? '欠' : ''
  n = Math.abs(n)
  let s = ''
  for (let i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(Math.floor(n * 1000 * 10 * Math.pow(10, i)) % (10 * 1000) / 1000)] + fraction[i]).replace(/零./, '')
  }
  s = s || '整'
  n = Math.floor(n)
  for (let i = 0; i < unit[0].length && n > 0; i++) {
    let p = ''
    for (let j = 0; j < unit[1].length && n > 0; j++) {
      p = digit[n % 10] + unit[1][j] + p
      n = Math.floor(n / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  return head + s.replace(/(零.)*零元/, '元')
    .replace(/(零.)+/g, '零')
    .replace(/^整$/, '零元整')
}

// 生成随机 字母+ 数字 串
export function randomRange (min, max) {
  var returnStr = "",
    range = max ? Math.round(Math.random() * (max - min)) + min : min,
    arr = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z",
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
      "G",
      "H",
      "I",
      "J",
      "K",
      "L",
      "M",
      "N",
      "O",
      "P",
      "Q",
      "R",
      "S",
      "T",
      "U",
      "V",
      "W",
      "X",
      "Y",
      "Z"
    ];
  for (var i = 0; i < range; i++) {
    var index = Math.round(Math.random() * (arr.length - 1));
    returnStr += arr[index];
  }

  return returnStr;
}



//  根据对象值获取对象key
export function getFindKey (value, obj, me) {
  let objlist = JSON.parse(JSON.stringify(obj));
  delete objlist.me;
  let findKey = (value, compare = (a, b) => a === b) => {
    return Object.keys(objlist).find(k => compare(objlist[k], value))
  }
  return findKey(value);
}

